<template>


  <div class="login-container">


    <el-card class="login-card">
      <h2 class="login-title">系统登录</h2>
      <el-form
        ref="formRef"
        @keyup.enter="handleLogin"
      >
        <!-- 手机号输入框 -->
        <el-form-item>
          <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item>
          <el-input
            v-model="loginForm.password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <!-- 图片验证码输入框 -->
        <el-form-item class="code-input">
          <el-input
            v-model="loginForm.imgcode"
            placeholder="请输入图片验证码"
          />
          <div class="image-code" @click="refreshImageCode">
            <img :src="imageCodeUrl" alt="验证码">
          </div>
          <el-button
            type="primary"
            @click="refreshImageCode"
          >
            刷新
          </el-button>
        </el-form-item>

        <!-- 验证码输入框 -->
        <el-form-item class="code-input">
          <el-input
            v-model="loginForm.code"
            placeholder="请输入验证码"
          />
          <el-button
            type="primary"
            class="send-btn"
            @click="sendCode"
            :disabled="isSending"
          >
            {{ isSending ? `${countdown}秒后重试` : '获取验证码' }}
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleLogin"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>

        <!-- 钉钉登录按钮 -->
        <el-form-item>
          <div class="dingtalk-login-container">
            <div class="dingtalk-btn" @click="dingtalkLogin">
              <svg class="dingtalk-icon" viewBox="0 0 1024 1024">
                <path d="M512 0C229.23 0 0 229.23 0 512s229.23 512 512 512 512-229.23 512-512S794.77 0 512 0z m269.312 676.096c-50.176 0-90.112-39.936-90.112-90.112s39.936-90.112 90.112-90.112 90.112 39.936 90.112 90.112-39.936 90.112-90.112 90.112zM380.416 429.568c-50.176 0-90.112-39.936-90.112-90.112s39.936-90.112 90.112-90.112 90.112 39.936 90.112 90.112-39.936 90.112-90.112 90.112z m243.712 0c-50.176 0-90.112-39.936-90.112-90.112s39.936-90.112 90.112-90.112 90.112 39.936 90.112 90.112-39.936 90.112-90.112 90.112zM242.688 676.096c-50.176 0-90.112-39.936-90.112-90.112s39.936-90.112 90.112-90.112 90.112 39.936 90.112 90.112-39.936 90.112-90.112 90.112z" fill="#1296DB"></path>
              </svg>
              <span>钉钉登录</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="success"
            @click="Giteelogin"
            style="width: 100%"
          >
            Gitee登录
          </el-button>

        </el-form-item>
        <el-form-item>
          <el-button type="text" @click="goAdminLogin" style="width: 100%">
            切换到管理员登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
// 表单数据
const loginForm = reactive({
  phone: '',
  password: '',
  code: '',
  remember: false,
  imgcode: ''
})

const loading = ref(false)
const isSending = ref(false)
const countdown = ref(60)
let timer = null

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      isSending.value = false
    }
  }, 1000)
}

// 发送验证码
const sendCode = async () => {
  if (!loginForm.phone) {
    ElMessage.warning('请输入手机号')
    return
  }

  if (!loginForm.imgcode) {
    ElMessage.warning('请输入图片验证码')
    refreshImageCode()
    return
  }

  try {
    // 1. 首先验证图片验证码
    const verifyResponse = await axios.post('http://127.0.0.1:8000/login/verify/', {
      captcha: loginForm.imgcode
    })

    if (!verifyResponse.data.valid) {
      ElMessage.warning('图片验证码错误，请重试')
      refreshImageCode()
      return
    }

    // 2. 验证通过后发送短信验证码
    isSending.value = true
    const sendResponse = await axios.get('http://127.0.0.1:8000/login/sendcode/', {
      params: { phone: loginForm.phone }
    })

    if (sendResponse.status === 200) {
      ElMessage.success('验证码发送成功')
      startCountdown()
    } else {
      ElMessage.error('验证码发送失败')
      isSending.value = false
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    let errorMsg = '验证码发送失败'

    if (error.response) {
      if (error.response.status === 400) {
        errorMsg = '请求参数错误'
      } else if (error.response.status === 500) {
        errorMsg = '服务器内部错误'
      }

      if (error.response.data && error.response.data.message) {
        errorMsg += `: ${error.response.data.message}`
      }
    } else if (error.request) {
      errorMsg = '无法连接到服务器'
    }

    ElMessage.error(errorMsg)
    isSending.value = false
  }
}

// 图片验证码URL
const imageCodeUrl = ref('http://127.0.0.1:8000/login/image/')

// 刷新图片验证码 - 修复方法
const refreshImageCode = () => {
  // 添加时间戳参数确保每次都获取新图片
  imageCodeUrl.value = `http://127.0.0.1:8000/login/image/?t=${Date.now()}`
}

// 登录方法
const handleLogin = async () => {
  if (!loginForm.phone || !loginForm.password || !loginForm.code) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    loading.value = true
    const response = await axios.post('http://127.0.0.1:8000/login/login/', {
      phone: loginForm.phone,
      password: loginForm.password,
      code: loginForm.code
    })

    if (response.data.code === 200) {
      ElMessage.success(response.data.msg)
      localStorage.setItem('user_id', response.data.userid)
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('retoken', response.data.retoken)
      localStorage.setItem('phone', loginForm.phone) // 存储手机号作为用户标识
          // 登录成功
      localStorage.setItem('role', 'user')   // 这里！
      // 其他信息也可以存

      // 直接跳转到首页，不再刷新页面
      router.push('/').then(() => {
            // 然后执行全局刷新
            window.location.reload()
      })
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    console.error('登录失败:', error)
    let errorMsg = '登录失败，请检查输入'

    if (error.response) {
      if (error.response.data && error.response.data.msg) {
        errorMsg = error.response.data.msg
      }
    }

    ElMessage.error(errorMsg)
  } finally {
    loading.value = false
  }
}

// 钉钉登录
const dingtalkLogin = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:8000/login/dingtalkauth/')
    if (response.data.auth_url) {
      window.location.href = response.data.auth_url
    } else {
      ElMessage.error('获取钉钉登录链接失败')
    }
  } catch (error) {
    console.error('钉钉登录失败:', error)
    ElMessage.error('钉钉登录失败，请稍后重试')
  }
}

//Gitee登录
const Giteelogin =async () => {
  try {
    const response = await axios.get('http://127.0.0.1:8000/login/giteelogin/')
    if (response.data.auth_url) {
      window.location.href = response.data.auth_url
    } else {
      ElMessage.error('获取Gitee登录链接失败')
    }
  } catch (error) {
    console.error('Gitee登录失败:', error)
    ElMessage.error('Gitee登录失败，请稍后重试')
  }
}

const goAdminLogin = () => {
  router.push('/houlogin') // 跳转到管理员登录页面
}

onMounted(() => {
  // 初始加载时刷新验证码
  refreshImageCode()
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-card {
  width: 400px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 24px;
  color: #409eff;
}

.code-input {
  display: flex;
  align-items: center;
}

.code-input .el-input {
  flex: 1;
  margin-right: 10px;
}

.send-btn {
  width: 120px;
}

.image-code {
  cursor: pointer;
  margin-right: 10px;
  height: 40px;
}

.image-code img {
  height: 100%;
}

/* 钉钉登录按钮样式 */
.dingtalk-login-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dingtalk-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 40px;
  background-color: #1296DB;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-weight: 500;
}

.dingtalk-btn:hover {
  background-color: #0d7bbf;
}

.dingtalk-icon {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

</style>